//
//  UserCenterViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/10/9.
//

import UIKit

class UserCenterViewController: BaseViewController {
    var zhBtn: UIButton = {
        var btn = UIButton()
        btn.setup_titleLabel(text: "简体")
        btn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        return btn
    }()
    var logOut: UIButton!
    var tableView: BaseTableView!
    var userInfoData: UserInfoDataModel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.inintTableView()
        self.tabbarView()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.fetchGetUserInfo()
    }
    
    func inintTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight), style: .grouped)
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.backgroundColor = .white
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(MemberInfoTableViewCell.self, forCellReuseIdentifier: "MemberInfoTableViewCell")
        self.tableView.register(MyEntranceTableViewCell.self, forCellReuseIdentifier: "MyEntranceTableViewCell")
        self.tableView.register(CommonTableViewCell.self, forCellReuseIdentifier: "CommonTableViewCell")
        self.tableView.register(CommonTableViewCell.self, forCellReuseIdentifier: "CommonTableViewCell2")
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "space")
        self.view.addSubview(self.tableView)
    }
    
    func tabbarView(){
       let bgView = UIView(frame: CGRect(x: 0, y: kScreenHeight - TabbarHeight, width: kScreenWidth, height: TabbarHeight))
        bgView.backgroundColor = .white
        self.view.addSubview(bgView)
        
        logOut = UIButton(frame: CGRect(x: 14, y: 10, width: kScreenWidth - 28, height: 44))
        logOut.backgroundColor = .white
        logOut.addTarget(self, action: #selector(logOutAction), for: .touchUpInside)
        let bgLayer1 = CALayer()
        bgLayer1.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor
        logOut.layer.addSublayer(bgLayer1)
        // shadowCode
        logOut.layer.shadowColor = UIColor(red: 0.96, green: 0.96, blue: 0.98, alpha: 0.9).cgColor
        logOut.layer.shadowOffset = CGSize(width: 0, height: 0)
        logOut.layer.shadowOpacity = 1
        logOut.layer.shadowRadius = 10
        logOut.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        logOut.layer.cornerRadius = 8
        logOut.setup_titleLabel(text: MMLocalizedString("log_out", comment: "退出登录"))
        logOut.setTitleColor(Theme.titleLabColor, for: .normal)
        bgView.addSubview(logOut)
        bgLayer1.frame = logOut.bounds
    }
    
    ///获取个人信息
    func fetchGetUserInfo(){
        if self.userInfoData == nil {
            self.view.showLoadingHUDText(nil)
        }
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.memberGetDetail, objectType: UserInfoResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! UserInfoResModel
            if resultObj.code == "1" {
                self.userInfoData = resultObj.data
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
            self.tableView.reloadData()
        } error: { err in
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? MMLocalizedString("request_failed", comment: "请求失败，请稍候再试"))
        }
    }
    
    
 
    ///退出
    @objc func logOutAction(){
        XTAlertView.showAlertView(title: MMLocalizedString("add_tip", comment: "提示"),
                                  message: MMLocalizedString("", comment: "确认退出？"),
                                  cancelButtonTitle: MMLocalizedString("cancel", comment: "取消"),
                                  otherButtonTitlesArr: [MMLocalizedString("confirm", comment: "确定")])
        { alertView, buttonIndex in
            if buttonIndex == 1 {
                self.jumpHomePage()
            }
        }
    }
    
    ///跳转到首页，再跳登录页
    func jumpHomePage() {
        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        self.navigationController?.popToRootViewController(animated: false)
        tabbarVC.selectedIndex = 0
        UserModule.shared.isLogined = false
        XTManageCenter.shared.jumpToLoginView()
    }
}

extension UserCenterViewController: UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
        switch indexPath.section {
            case 0:
                let cell = tableView.dequeueReusableCell(withIdentifier: "MemberInfoTableViewCell", for: indexPath) as! MemberInfoTableViewCell
                if self.userInfoData != nil{
                    cell.setModel(model: self.userInfoData)
                }
                return cell
            case 1:
                let cell = tableView.dequeueReusableCell(withIdentifier: "MyEntranceTableViewCell", for: indexPath) as! MyEntranceTableViewCell
                return cell
            case 2:
                let cell = tableView.dequeueReusableCell(withIdentifier: "CommonTableViewCell", for: indexPath) as! CommonTableViewCell
                cell.leftImageView.image = UIImage(named: "icon_referral_code")
                cell.titleLab.text = MMLocalizedString("referral_code", comment: "推荐码")
                cell.rightImageView.image = UIImage(named: "icon_code_con")
                cell.contentLab.text = self.userInfoData?.referralCode ?? ""
                cell.updateRightImage()
                return cell
            case 3:
                let cell = tableView.dequeueReusableCell(withIdentifier: "CommonTableViewCell2", for: indexPath) as! CommonTableViewCell
                cell.leftImageView.image = UIImage(named: "icon_set_user")
                cell.titleLab.text = MMLocalizedString("setting", comment: "设置")
                cell.rightImageView.image = UIImage(named: "icon_arrow_right_black")
                cell.contentLab.text = ""
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: "space", for: indexPath)
                return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
          headerView.backgroundColor = .clear
        return headerView
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        footerView.backgroundColor = .clear
        return footerView
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.section {
        case 2:
            let past = UIPasteboard.general//系统自带的复制
            past.string = self.userInfoData?.referralCode ?? ""
            self.view.makeToast(message: MMLocalizedString("copy_successed", comment: "复制成功"))
        case 3:
            let vc = SettingViewController()
            vc.phoneStr =  self.userInfoData?.account ?? ""
            self.navigationController?.pushViewController(vc, animated: true)
        default:
          ()
        }
    }
    
}
